package com.dys.designpattern.singleton.threadpool;

import java.io.Serializable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 疾风
 * @ClassName: ThreadPoolConfig
 * @Description: 线程池创建类
 * @CreateDate: 2024/05/11
 * @Version: v1.0.0
 */
public class ThreadPoolConfig implements Serializable {
    // 核心线程数
    private static final int corePoolSize = 32;
    // 最大线程数
    private static final int maxPoolSize = 48;
    // 线程最大空闲时间
    private static final int keepAlive = 30;
    // 线程池缓冲队列
    private static final BlockingQueue poolQueue = new LinkedBlockingQueue(64);
    private static ThreadPoolExecutor POOL_EXECUTOR;

    private ThreadPoolConfig() {
        if (POOL_EXECUTOR!=null) {
            throw new RuntimeException("不允许非法访问");
        }
    }

    /**
     * 单例模式获取
     *
     * @return
     */
    public static ThreadPoolExecutor getInstance() {
        if (POOL_EXECUTOR == null) {
            // 使用synchronized保证多线程情况下也是单例的
            synchronized (ThreadPoolConfig.class) {
                if (POOL_EXECUTOR == null) {
                    POOL_EXECUTOR = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAlive, TimeUnit.SECONDS, poolQueue, new
                            ThreadPoolExecutor.DiscardOldestPolicy());
                }
            }
        }
        return POOL_EXECUTOR;
    }

    private Object readResolve() {
        return POOL_EXECUTOR;
    }
}
